package website.lucaswork.survey.mvc.validators;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import website.lucaswork.survey.core.converters.StringToLocalDateTimeConverter;
import website.lucaswork.survey.core.services.UserService;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = LocalDateTimeFormat.LocalDateTimeFormatValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface LocalDateTimeFormat {

    String message() default "Input datetime is invalid";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    public class LocalDateTimeFormatValidator implements ConstraintValidator<LocalDateTimeFormat, String> {

        @Autowired
        StringToLocalDateTimeConverter converter;

        @Override
        public void initialize(LocalDateTimeFormat name) {

        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            try {
                converter.convert(s);
            } catch(Exception e) {
                return false;
            }
            return true;
        }
    }
}
